package com.rjwh.dingdong.client.activity.community;

import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.os.Bundle;
import android.support.design.widget.AppBarLayout;
import android.support.v7.widget.Toolbar;
import android.view.KeyEvent;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.ImageButton;
import android.widget.LinearLayout;
import android.widget.ProgressBar;
import android.widget.RelativeLayout;

import com.aishua.lib.utils.AsStrUtils;
import com.rjwh.dingdong.client.R;
import com.rjwh.dingdong.client.activity.BaseActivity;
import com.rjwh.dingdong.client.activity.loginregist.ThirdPartyLoginActivity;
import com.rjwh.dingdong.client.application.MyApplication;
import com.rjwh.dingdong.client.constant.LocalConstant;
import com.rjwh.dingdong.client.mvp.presenter.impl.CommunityPostDetailPresenter;
import com.rjwh.dingdong.client.mvp.view.CommunityPostDetailView;
import com.rjwh.dingdong.client.util.LogUtil;
import com.rjwh.dingdong.client.util.RxBus;
import com.rjwh.dingdong.client.util.ShareUtil;
import com.rjwh.dingdong.client.view.BaseWebView;
import com.tencent.smtt.export.external.interfaces.JsResult;
import com.tencent.smtt.sdk.WebChromeClient;
import com.tencent.smtt.sdk.WebView;
import com.tencent.smtt.sdk.WebViewClient;

import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import cn.sharesdk.framework.ShareSDK;
import rx.Observable;
import rx.android.schedulers.AndroidSchedulers;
import rx.functions.Action1;

import static android.view.View.GONE;
import static android.view.View.VISIBLE;

/**
 * 社区-帖子详情
 *
 * @author 王小珂
 * @ClassName CommunityPostDetailActivity
 * @Description TODO(这里用一句话描述这个类的作用)
 * @date 2016-4-26 下午3:32:08 2
 * @history 1.YYYY-MM-DD author: description:
 */
public class CommunityPostDetailActivity extends BaseActivity implements CommunityPostDetailView {
    @BindView(R.id.toolbar)
    Toolbar toolbar;
    @BindView(R.id.app_bar_layout)
    AppBarLayout appBarLayout;
    @BindView(R.id.btn_refresh)
    Button btnRefresh;
    @BindView(R.id.error_layout)
    RelativeLayout errorLayout;
    @BindView(R.id.community_post_detail_webview)
    BaseWebView webView;
    @BindView(R.id.community_post_detail_reply_root_ll)
    LinearLayout reply_root_ll;
    @BindView(R.id.community_post_detail_heart_cb)
    ImageButton zanBtn;
    @BindView(R.id.community_post_detail_progressbar)
    ProgressBar communityPostDetailProgressbar;
    private MenuItem favouriteView;
    private MenuItem shareView;

    private String rootUrl;
    private String topicid;
    private String shareTitle;
    private String shareUrl;
    private String sharepic;
    private String shareIntroduction;
    private static final int REQUESTCODE = 321;
    private boolean isDoPraise;//是否为点赞操作
    private boolean isZan;//是否已点赞

    private boolean isFavor;//是否已收藏
    private CommunityPostDetailPresenter presenter;
    private Observable<Integer> observable;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.community_post_detail_layout);
        ButterKnife.bind(this);
        ShareSDK.initSDK(this);
        parseIntent();
        startObserver();
        initView();
        presenter = new CommunityPostDetailPresenter(this, this);
    }

    public static void startActivity(Context context, String url, String topicid) {
        Intent intent = new Intent(context, CommunityPostDetailActivity.class);
        intent.putExtra("url", url);
        intent.putExtra("topicid", topicid);
        context.startActivity(intent);
    }

    private void parseIntent() {
        Intent intent = getIntent();
        if (intent != null) {
            rootUrl = intent.getStringExtra("url");
            topicid = intent.getStringExtra("topicid");
        }
    }

    private void initView() {
        initToolbarHelper();
        reply_root_ll.setVisibility(View.GONE);
        webView.setWebViewClient(new WebViewClient() {
            @Override
            public boolean shouldOverrideUrlLoading(WebView view, String url) {
                return presenter.shouldOverrideUrl(url);
            }

            @SuppressWarnings("deprecation")
            @Override
            public void onReceivedError(WebView view, int errorCode, String description, String failingUrl) {
                super.onReceivedError(view, errorCode, description, failingUrl);
                showErrorView();
                reply_root_ll.setVisibility(View.GONE);
            }

            @Override
            public void onPageStarted(WebView view, String url, Bitmap favicon) {
                super.onPageStarted(view, url, favicon);
            }

            @Override
            public void onPageFinished(WebView view, String url) {
                super.onPageFinished(view, url);
//                hideErrorView();
                reply_root_ll.setVisibility(View.VISIBLE);
                // 获取点赞和收藏状态
                if (MyApplication.spUtil.getBoolPreferenceByParamName(CommunityPostDetailActivity.this, LocalConstant.SP_IS_LOGINED)) {
                    presenter.doGetPostBasicData(topicid);
                } else {
                    //未登录状态
                    hideLoadingView();
                    showMenuItems();
                }
            }
        });
        webView.setWebChromeClient(new WebChromeClient() {

            @Override
            public void onReceivedTitle(WebView view, String title) {
                super.onReceivedTitle(view, title);
                if (getSupportActionBar() != null && !AsStrUtils.isEmpty(title)) {
                    getSupportActionBar().setTitle(title);
                }
            }

            @Override
            public boolean onJsAlert(WebView view, String url, String message, JsResult result) {
                return super.onJsAlert(view, url, message, result);
            }

            @Override
            public void onProgressChanged(WebView webView, int i) {
                if (i == 100) {
                    communityPostDetailProgressbar.setVisibility(GONE);
                } else {
                    if (communityPostDetailProgressbar.getVisibility() == GONE) {
                        communityPostDetailProgressbar.setVisibility(VISIBLE);
                        communityPostDetailProgressbar.setProgress(i);
                    }
                }
                super.onProgressChanged(webView, i);
            }
        });

        if (!AsStrUtils.isEmpty(rootUrl)) {
            LogUtil.e("CommunityPostDetailActivity", "rootUrl: " + rootUrl);
            LogUtil.e("CommunityPostDetailActi", "rootUrl: " + rootUrl);
            webView.loadUrl(rootUrl);
        }
    }

    /**
     * init the toolbar
     */
    protected void initToolbarHelper() {
        this.setSupportActionBar(this.toolbar);
        assert getSupportActionBar() != null;
        getSupportActionBar().setHomeButtonEnabled(true); //设置返回键可用
        getSupportActionBar().setDisplayHomeAsUpEnabled(true);
        toolbar.setNavigationOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (webView.canGoBack()) {
                    webView.goBack();// 返回上一页面
                } else {
                    CommunityPostDetailActivity.this.finish();
                }
            }
        });
    }

    private void startObserver() {
        observable = RxBus.get().register(LocalConstant.RX__POST_LOGIN_UPDATE_UI, Integer.class);
        observable.observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Action1<Integer>() {
                               @Override
                               public void call(Integer type) {
                                   presenter.doGetPostBasicData(topicid);
                               }
                           }, new Action1<Throwable>() {
                               @Override
                               public void call(Throwable throwable) {
                                   LogUtil.d("CommunityPostDetailActivity", "observable error: " + throwable.getMessage());
                               }
                           }
                );
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        this.getMenuInflater().inflate(R.menu.menu_community_posts_detail, menu);
        return true;
    }

    @Override
    public boolean onPrepareOptionsMenu(Menu menu) {
        // TODO Auto-generated method stub
        favouriteView = menu.findItem(R.id.menu_posts_favorite);// .setIcon(R.drawable.ic_camera);
        shareView = menu.findItem(R.id.menu_posts_share);
        favouriteView.setVisible(false);
        shareView.setVisible(false);
        return super.onPrepareOptionsMenu(menu);
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        boolean isLogined = MyApplication.spUtil.getBoolPreferenceByParamName(CommunityPostDetailActivity.this, LocalConstant.SP_IS_LOGINED);
        switch (item.getItemId()) {
            case R.id.menu_posts_favorite:
                if (isLogined) {
                    showLoadDialog();
                    isDoPraise = false;
                    if (isFavor) {
                        presenter.doCollection(topicid, "1");
                    } else {
                        presenter.doCollection(topicid, "2");
                    }
                } else {
                    ThirdPartyLoginActivity.startActivity(this);
                }
                return true;
            case R.id.menu_posts_share:
                if (isLogined) {
                    //打开一键分享
                    LogUtil.e("CommunityPostDetailActi", shareTitle + ";" + shareIntroduction + ";" + shareUrl + ";" + sharepic);
                    ShareUtil.showShare(CommunityPostDetailActivity.this, shareTitle, shareIntroduction, shareUrl, sharepic);
                } else {
                    ThirdPartyLoginActivity.startActivity(this);
                }
                return true;
        }
        return super.onOptionsItemSelected(item);
    }

    @Override
    public void showLoadingView() {
        if (communityPostDetailProgressbar != null) {
            communityPostDetailProgressbar.setVisibility(View.VISIBLE);
        }
    }

    @Override
    public void hideLoadingView() {
        if (communityPostDetailProgressbar != null) {
            communityPostDetailProgressbar.setVisibility(View.GONE);
        }
    }

    @Override
    public void showErrorView() {
        if (errorLayout != null) {
            errorLayout.setVisibility(View.VISIBLE);
        }
    }

    @Override
    public void hideErrorView() {
        if (errorLayout != null) {
            errorLayout.setVisibility(View.GONE);
        }
    }

    @Override
    public void loadUrl(String url) {
        webView.loadUrl(url);
    }

    /**
     * @return 是否已点赞
     */
    @Override
    public boolean getPraiseCheck() {
        return isZan;
    }

    /**
     * @return 是否执行点赞操作(区别收藏操作)
     */
    @Override
    public boolean isDoParise() {
        return isDoPraise;
    }

    /**
     * 进入界面后更新按钮状态
     *
     * @param isfavorited 是否已收藏
     * @param ispraised   是否已点赞
     */
    @Override
    public void initPraiseViewState(String isfavorited, String ispraised) {
        if (!AsStrUtils.isEmpty(isfavorited)) {
            if (isfavorited.equals("1")) {
                isFavor = false;
                favouriteView.setIcon(R.drawable.icon_favorite_star_checked);
            } else {
                isFavor = true;
                favouriteView.setIcon(R.drawable.icon_favorite_star_normal);
            }
        }
        // 默认为 0未点赞, 1点赞
        if (!AsStrUtils.isEmpty(ispraised)) {
            if (ispraised.equals("1")) {
                isZan = false;
                zanBtn.setImageResource(R.drawable.icon_zan_heart_checked);
            } else {
                isZan = true;
                zanBtn.setImageResource(R.drawable.icon_zan_heart_normal);
            }
        }
    }

    @Override
    public void loadShareData(String title, String introduction, String sharefilepath, List<String> image) {
        if (title != null) {
            this.shareTitle = title;
        } else {
            this.shareTitle = "";
        }
        if (introduction != null) {
            this.shareIntroduction = introduction;
        } else {
            this.shareIntroduction = "";
        }
        if (sharefilepath != null) {
            this.shareUrl = sharefilepath;
        }
        if (image != null && !image.isEmpty()) {
            this.sharepic = image.get(0);
        } else {
            sharepic = "";
        }
    }

    /**
     * 更新点赞按钮状态
     *
     * @param isZan 是否点赞
     */
    @Override
    public void setZanBtnChecked(boolean isZan) {
        dismissLoadDialog();
        if (isZan) {
            this.isZan = false;
            zanBtn.setImageResource(R.drawable.icon_zan_heart_checked);
        } else {
            this.isZan = true;
            zanBtn.setImageResource(R.drawable.icon_zan_heart_normal);
        }
    }

    /**
     * s是否已收藏
     *
     * @return
     */
    @Override
    public boolean getFavorCheck() {
        return isFavor;
    }

    /**
     * 更新收藏按钮状态
     *
     * @param isFavor
     */
    @Override
    public void setFavourBtnCheck(boolean isFavor) {
        dismissLoadDialog();
        if (isFavor) {
            this.isFavor = false;
            favouriteView.setIcon(R.drawable.icon_favorite_star_checked);
        } else {
            this.isFavor = true;
            favouriteView.setIcon(R.drawable.icon_favorite_star_normal);
        }
    }

    /**
     * 显示toolbar上的按钮
     */
    @Override
    public void showMenuItems() {
        if (favouriteView != null) {
            favouriteView.setVisible(true);
        }
        if (shareView != null) {
            shareView.setVisible(true);
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == RESULT_OK) {
            if (data == null) {
                return;
            }
            String postid = data.getStringExtra("postid");
            webView.loadUrl(rootUrl + "&postid=" + postid);
            webView.postDelayed(new Runnable() {
                @Override
                public void run() {
                    // 回复后清除历史记录
                    webView.clearHistory();
                }
            }, 1000);
        }
    }

    @OnClick({R.id.community_post_detail_reply_tv, R.id.community_post_detail_heart_cb})
    public void onClick(View view) {
        if (MyApplication.spUtil.getBoolPreferenceByParamName(CommunityPostDetailActivity.this, LocalConstant.SP_IS_LOGINED)) {
            switch (view.getId()) {
                case R.id.community_post_detail_reply_tv:
                    Intent intent = new Intent(CommunityPostDetailActivity.this, CommunityPostPublishActivity.class);
                    intent.putExtra("isReply", true);
                    intent.putExtra("topicid", topicid);
                    intent.putExtra("replyid", "0");
                    intent.putExtra("parentid", "0");
                    startActivityForResult(intent, REQUESTCODE);
                    break;
                case R.id.community_post_detail_heart_cb:
                    showLoadDialog();
                    isDoPraise = true;
                    if (isZan) {
                        presenter.doPraise(topicid, "1");
                    } else {
                        presenter.doPraise(topicid, "2");
                    }
                    break;
            }
        } else {
            ThirdPartyLoginActivity.startActivity(this);
        }
    }

    @OnClick(R.id.btn_refresh)
    public void onClick() {
        webView.reload();
        hideErrorView();
        reply_root_ll.setVisibility(GONE);
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        // TODO Auto-generated method stub
        if (keyCode == KeyEvent.KEYCODE_BACK) {
            if (webView.canGoBack()) {
                webView.goBack();// 返回上一页面
                return true;
            } else {
                setResult(RESULT_OK);
            }
        }
        return super.onKeyDown(keyCode, event);
    }

    @Override
    protected void onDestroy() {
        presenter.detachView();
        ShareSDK.stopSDK(this);
        RxBus.get().unregister(LocalConstant.RX__POST_LOGIN_UPDATE_UI, observable);
        if (webView != null) {
            webView.setVisibility(View.GONE);
            webView.removeAllViews();
            webView.destroy();
        }
        super.onDestroy();
    }

}